
package com.quyang.voice.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyang.voice.dao.CustAccountbaseMapper;
import com.quyang.voice.manage.ICustAccountbaseManage;
import com.quyang.voice.model.*;
import com.quyang.voice.service.*;
import com.quyang.voice.utils.ResponseUtil;
import com.quyang.voice.utils.ResultCode;
import com.quyang.voice.utils.ReturnJson;
import com.quyang.voice.utils.SafeUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.quyang.voice.utils.ResultCode.SUCCESS;

@Service("cust_accountbaseService")
public class CustAccountbaseServiceImpl extends ServiceImpl<CustAccountbaseMapper, CustAccountbase> implements ICustAccountbaseService {

    private static final Logger logger = LoggerFactory.getLogger(CustAccountbaseServiceImpl.class);


    @Autowired
    ICustAccountbaseService custAccountbaseService;


    @Autowired
    ICustAccountbaseManage custAccountbaseManage;

    @Autowired
    CustAccountbaseMapper custAccountbaseMapper;

    @Autowired
    IConsumeRecordService consumeRecordService;

    @Autowired
    IAppConfigService appConfigService;

    @Autowired
    LitemallOrderService orderService;

    @Autowired
    IMissuUsersService missuUsersService;


    @Override
    public ResponseUtil<Map> getCustAccountbaseById(@PathVariable("id") Integer id){
        try {
            QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
            custAccountbaseQueryWrapper.select("SUM(amount) as amount, SUM(integral) as integral");
            custAccountbaseQueryWrapper.eq("user_id",id);
            Map<String, Object> map = custAccountbaseService.getMap(custAccountbaseQueryWrapper);
            if (ObjectUtils.isEmpty(map)){
                map = new HashMap<>();
                map.put("amount",0);
            }

            return ResponseUtil.suc(map);
        }catch (Exception e){
            logger.error("CustAccountbaseServiceImpl.getCustAccountbaseById", e);
            return ResponseUtil.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ReturnJson recharge(HttpServletRequest request, HttpServletResponse response) {
        AppConfig appConfig = appConfigService.getOne(null);

        try {
            logger.info("支付宝开始回调");
            //设置response格式
            response.setContentType("text/html;charset=UTF-8");
            Map<String, String> paramsMap = SafeUtils.convertRequestParamsToMap(request);  //将异步通知中收到的待验证所有参数都存放到map中
            if ("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                // TODO 验签成功后
                //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
                response.getWriter().write("success");
            } else {
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                response.getWriter().write("failure");
            }

            //方法返回值要设为void，否则与response关闭方法冲突报错
            response.getWriter().close();

            //从passback_params获取参数
            String params=request.getParameter("passback_params");
            String[] paramsList= URLDecoder.decode(params,"UTF-8").split("&");
            Long userId= Long.valueOf(paramsList[0].split("=")[1]);
            Double number=Double.valueOf(paramsList[1].split("=")[1]);
            Integer phoneType=Integer.valueOf(paramsList[2].split("=")[1]);
            Integer accountType=Integer.valueOf(paramsList[3].split("=")[1]);

            //生成交易流水号
            String orderId = paramsMap.get("out_trade_no");

            //写入钱包和交易记录
//            Double momey = Integer.valueOf((int) (number * 100)) ;
            QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
            custAccountbaseQueryWrapper.eq("user_id",userId);
            CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
            custAccountbase.setAmount(custAccountbase.getAmount() + number);

            //写入交易记录
//            QueryWrapper<ConsumeRecord> consumeRecordQueryWrapper = new QueryWrapper<>();
//            consumeRecordQueryWrapper.eq("user_id",userId);
            ConsumeRecord consumeRecord = new ConsumeRecord();
            consumeRecord.setMoney(number);
            consumeRecord.setTradeNo(orderId);
            consumeRecord.setPayType(accountType);
            consumeRecord.setPayType(1);
            consumeRecord.setUserId(userId);
            consumeRecord.setCurrentBalance(custAccountbase.getAmount() + number);
            consumeRecord.setChangeType(1);
            consumeRecord.setType(1);
            consumeRecord.setMoney(number);
            consumeRecord.setOperationAmount(number);
            consumeRecord.setStatus(1);
            consumeRecord.setTime(new Date());
            consumeRecord.setDescs("用户充值");
            custAccountbaseService.updateById(custAccountbase);
            consumeRecordService.save(consumeRecord);
            logger.info("支付宝回调成功");
            return null;
        } catch (IOException e) {
            logger.error("WalletServiceImpl.recharge: "+e);
            e.printStackTrace();
            return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ReturnJson shopPayment(HttpServletRequest request, HttpServletResponse response) {
        AppConfig appConfig = appConfigService.getOne(null);

        try {
            logger.info("支付宝开始回调");
            //设置response格式
            response.setContentType("text/html;charset=UTF-8");
            Map<String, String> paramsMap = SafeUtils.convertRequestParamsToMap(request);  //将异步通知中收到的待验证所有参数都存放到map中
            if ("TRADE_SUCCESS".equals(paramsMap.get("trade_status"))){
                // TODO 验签成功后
                //按照支付结果异步通知中的描述，对支付结果中的业务内容进行1\2\3\4二次校验，校验成功后在response中返回success，校验失败返回failure
                response.getWriter().write("success");
            } else {
                // TODO 验签失败则记录异常日志，并在response中返回failure.
                response.getWriter().write("failure");
            }

            //方法返回值要设为void，否则与response关闭方法冲突报错
            response.getWriter().close();
//
//            //从passback_params获取参数
//            String params=request.getParameter("passback_params");
//            String[] paramsList= URLDecoder.decode(params,"UTF-8").split("&");
//            Long userId= Long.valueOf(paramsList[0].split("=")[1]);
//            Double number=Double.valueOf(paramsList[1].split("=")[1]);
//            Integer phoneType=Integer.valueOf(paramsList[2].split("=")[1]);
//            Integer accountType=Integer.valueOf(paramsList[3].split("=")[1]);

            //生成交易流水号
            String orderId = paramsMap.get("out_trade_no");


            orderService.PayOrder(orderId);

//
//            //写入钱包和交易记录
////            Double momey = Integer.valueOf((int) (number * 100)) ;
//            QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
//            custAccountbaseQueryWrapper.eq("user_id",userId);
//            CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
//            custAccountbase.setAmount(custAccountbase.getAmount() + number);
//
//            //写入交易记录
////            QueryWrapper<ConsumeRecord> consumeRecordQueryWrapper = new QueryWrapper<>();
////            consumeRecordQueryWrapper.eq("user_id",userId);
//            ConsumeRecord consumeRecord = new ConsumeRecord();
//            consumeRecord.setMoney(number);
//            consumeRecord.setTradeNo(orderId);
//            consumeRecord.setPayType(accountType);
//            consumeRecord.setPayType(1);
//            consumeRecord.setUserId(userId);
//            consumeRecord.setCurrentBalance(custAccountbase.getAmount() + number);
//            consumeRecord.setChangeType(1);
//            consumeRecord.setType(1);
//            consumeRecord.setMoney(number);
//            consumeRecord.setOperationAmount(number);
//            consumeRecord.setStatus(1);
//            consumeRecord.setTime(new Date());
//            custAccountbaseService.updateById(custAccountbase);
//            consumeRecordService.save(consumeRecord);
            logger.info("支付宝回调成功");
            return null;
        } catch (IOException e) {
            logger.error("WalletServiceImpl.recharge: "+e);
            e.printStackTrace();
            return ReturnJson.fail(ResultCode.SYSTEM_ERROR);
        }
    }




    @Override
    public ReturnJson updatePayKey(Integer userId, String oldPayKey, String newPayKey) {
        QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
        custAccountbaseQueryWrapper.eq("user_id",userId);
        CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
        if (custAccountbase == null){
            CustAccountbase custAccountbaseNew = new CustAccountbase();
            custAccountbaseNew.setPayKey(newPayKey);
            custAccountbaseNew.setAmount(0.0);
            custAccountbaseNew.setUserId(userId.longValue());
            custAccountbaseNew.setFrozen(0.0);
            custAccountbaseService.save(custAccountbaseNew);
            return ReturnJson.suc(SUCCESS);
            //有钱包数据但是没有支付密码
        }else if (custAccountbase.getPayKey() == null || custAccountbase.getPayKey().equals("")){
            custAccountbase.setPayKey(newPayKey);
            custAccountbaseService.updateById(custAccountbase);
            return ReturnJson.suc(SUCCESS);
        }
        else {
            //判断老密码是否正确
            if (oldPayKey != null && custAccountbase.getPayKey().equals(oldPayKey)) {
                custAccountbase.setPayKey(newPayKey);
                custAccountbaseService.updateById(custAccountbase);
                return ReturnJson.suc(SUCCESS);
            }else
            {
                return  ReturnJson.fail(ResultCode.NO_CHECK_OLD_PAY_KEY);
            }
        }
    }


    @Override
    public ResponseUtil updatePayKey2(String phone, String payKey, String vCode) {



        return ResponseUtil.suc(SUCCESS);
    }

    @Override
    public ResponseUtil checkPayKeyIsExist(Integer userId) {
        QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
        custAccountbaseQueryWrapper.eq("user_id",userId);
        CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
        if (custAccountbase == null || custAccountbase.getPayKey() == null || custAccountbase.getPayKey().equals("")){
            return ResponseUtil.suc(0);
        }else {
            return ResponseUtil.suc(1);
        }

    }

    @Override
    public ResponseUtil checkPayKey(Integer userId, String payKey) {

        QueryWrapper<CustAccountbase> custAccountbaseQueryWrapper = new QueryWrapper<>();
        custAccountbaseQueryWrapper.eq("user_id",userId);
        CustAccountbase custAccountbase = custAccountbaseService.getOne(custAccountbaseQueryWrapper);
        if (StrUtil.isBlankIfStr(custAccountbase)) {
            createCustAccountbase(userId.longValue());
        }

        if (payKey.equals(custAccountbase.getPayKey())){
            return ResponseUtil.suc(1);
        }else {
            return ResponseUtil.suc(0);
        }
    }

    public void createCustAccountbase(Long userId){

        CustAccountbase custAccountbase = new CustAccountbase();

        custAccountbase.setUserId(userId);
        custAccountbase.setAmount(0D);
        custAccountbase.setFrozen(0D);
        custAccountbaseService.save(custAccountbase);

    }


}
